﻿#region File and License Information
/*
<File>
	<License>
		Copyright © 2009 - 2017, Daniel Vaughan. All rights reserved.
		This file is part of Calcium (http://calciumsdk.net), 
		which is released under the MIT License.
		See file /Documentation/License.txt for details.
	</License>
	<CreationDate>2013-04-18 14:08:48Z</CreationDate>
</File>
*/
#endregion

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;

namespace Outcoder.GeoLocation
{
	public sealed class GeolocatorProxy : IGeoLocator
	{
		readonly Geolocator geolocator = new Geolocator();

		public async Task<GeopositionWrapper> GetGeoCoordinateAsync()
		{
			Geoposition position = await geolocator.GetGeopositionAsync();
			return new GeopositionWrapper(position);
		}

		public async Task<GeopositionWrapper> GetGeoCoordinateAsync(
			TimeSpan maximumAge, TimeSpan timeout)
		{
			Geoposition position
				= await geolocator.GetGeopositionAsync(maximumAge, timeout);

			return new GeopositionWrapper(position);
		}

		public PositionAccuracy DesiredAccuracy
		{
			get
			{
				return geolocator.DesiredAccuracy;
			}
			set
			{
				geolocator.DesiredAccuracy = value;
			}
		}

		public PositionStatus LocationStatus
		{
			get
			{
				return geolocator.LocationStatus;
			}
		}

		public double MovementThresholdMeters
		{
			get
			{
				return geolocator.MovementThreshold;
			}
			set
			{
				geolocator.MovementThreshold = value;
			}
		}

		public uint ReportInterval
		{
			get
			{
				return geolocator.ReportInterval;
			}
			set
			{
				geolocator.ReportInterval = value;
			}
		}

		public void Start()
		{
			Stop();

			geolocator.PositionChanged += HandlePositionChanged;
			geolocator.StatusChanged += HandleStatusChanged;
		}

		public void Stop()
		{
			geolocator.PositionChanged -= HandlePositionChanged;
			geolocator.StatusChanged -= HandleStatusChanged;
		}

		public event EventHandler<StatusChangedProxyEventArgs> StatusChanged;

		void OnStatusChanged(StatusChangedProxyEventArgs e)
		{
			StatusChanged?.Invoke(this, e);
		}

		public event EventHandler<PositionChangedProxyEventArgs> PositionChanged;

		void OnPositionChanged(PositionChangedProxyEventArgs e)
		{
			PositionChanged?.Invoke(this, e);
		}

		void HandlePositionChanged(Geolocator sender, PositionChangedEventArgs args)
		{
			Debug.WriteLine("position changed " + args.Position.Coordinate);
			OnPositionChanged(new PositionChangedProxyEventArgs(
									new GeopositionWrapper(args.Position)));
		}

		void HandleStatusChanged(Geolocator sender, StatusChangedEventArgs args)
		{
			OnStatusChanged(new StatusChangedProxyEventArgs(args.Status));
		}
	}
}
